<script lang="ts" setup>
import { onMounted, ref, watch, reactive, computed } from 'vue';
import { DeviceServiceDetailResult, SpecificationResultFunction, SpecificationResultStatus } from '../interface';
import { h } from 'vue';
import FetchApi, { logdata } from '../../logs/api';
import { assign, throttle } from 'lodash-es';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus'
import { getExceltodownload } from '../../util/excel'
import { bizCode, statedata, statedata2 } from '../../tuyav2/statedata';
const props = defineProps<{
    device: DeviceServiceDetailResult,
    specificationFunction: SpecificationResultFunction[]
    specificationStatus: SpecificationResultStatus[],
    tuyastate: any
}>()

const activeName = ref("function");

const columns = ref([{
    title: '功能描述',
    dataIndex: 'name',
    key: 'name',
},
{
    title: 'Code',
    dataIndex: 'code',
    key: 'code',
},
{
    title: '类型',
    dataIndex: 'type',
    key: 'type',
},
{
    title: '取值范围',
    dataIndex: 'values',
    key: 'values',
    // scopedSlots: { customRender: 'pop' }, // 不起作用
    customRender: (data: any) => { // {text, record, index, column}
        let v = data?.text;
        if (data?.record?.type === "Boolean") {
            v = "{true,false}"
        } else {
            v = JSON.stringify(JSON.parse(data?.text), null, 2)
        }
        return h('pre', v)
    }
    // customCell: (data: any) => {
    //     console.log(data.name)
    //     return {
    //         style: {
    //             color: '#FF5733'
    //         }
    //     }
    // }
},])


const formInline = reactive<logdata>({
    query: "* | with_pack_meta",
    line: 10,
    offset: 0,
    projectName: "hterobot-tuya-iot",
    logstoreName: "tuya2",
    from: new Date(dayjs().subtract(32, "days").unix() * 1000),
    to: new Date(dayjs().add(1, "days").unix() * 1000),
    reverse: true,
});


const logcolumns = ref([{
    title: '时间',
    dataIndex: 'time',
    key: 'time',
    width: 150
},
{
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
},
{
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    width: 100
},
{
    title: '设备值',
    dataIndex: 'value',
    key: 'value',
}
])
const logtabledata = ref<{ time: string, name: string, type: string, value: string }[]>([])
const logcount = ref(0)
const offset = ref(0)
const _specificationFunction = ref<SpecificationResultFunction[]>([])
const _specificationStatus = ref<SpecificationResultStatus[]>([])

const loading = ref(false)

function getiotlogdata(offset: number) {
    loading.value = true
    FetchApi(assign({}, formInline, {
        query: `* | select * where devId in ('${props.device.id}') order by __time__ desc limit ${offset},100`,
    })).then(e => {
        logtabledata.value = e.data.map((e: Ilogdata) => {
            const time = dayjs(Number(e['__time__']) * 1000).format('MM-DD HH:mm')
            const iot = props.device
            const name = iot?.name || ''
            if (e.protocol == 4) {
                const _category1 = props.tuyastate.find(t => t.name === props.device.category && e['status0code'] === t.code)
                const category1 = props.specificationStatus.find(c => c.code === e['status0code'])
                const category2 = _specificationFunction.value.find(c => c.code === e['status0code'])
                let value = e['status0value']
                if (_category1) {

                    category1.type = _category1.type
                    category1.name = _category1.dataname || category1.name
                    category1.options = _category1.options || category1.range?.map(c => {
                        return {
                            option: c,
                            value: c
                        }
                    })


                }
                if (iot) {
                    if (category1?.type === 'Json') {
                        value = JSON.stringify(JSON.parse(value), null, 2)
                    } else {
                        value = statedata2(e['status0value'], category1, iot)

                    }
                }
                let type = category1?.name

                return {
                    time,
                    name,
                    type,
                    value
                }
            } else if (e.protocol == 20) {
                let type = '状态'
                let value = bizCode[e.bizcode]
                return {
                    time,
                    name,
                    type,
                    value
                }
            } else {
                return {
                    time,
                    name,
                    type: '',
                    value: ''
                }
            }

        })
        loading.value = false

    }).catch(c => {
        console.log(c)
    })
}


const time = computed({
    get(v) {
        return [dayjs(formInline.from), dayjs(formInline.to)]
    },
    set(c) {
        const [from, to] = c
        formInline.from = new Date(dayjs(from).subtract(32, "days").unix() * 1000)
        formInline.to = new Date(dayjs(to).subtract(32, "days").unix() * 1000)
    }
})

const current = ref(1)

function getlogcount() {

    FetchApi(assign({}, formInline, {
        query: `* | select count(*) as count where devId in ('${props.device.id}')`,
        line: 99
    })).then(e => {
        logcount.value = Number(e.data[0].count)
    }).catch(c => {
        console.log(c)
    })
}

watch(() => props.specificationFunction, e => {
    _specificationFunction.value = e
})
watch(() => props.specificationStatus, e => {
    _specificationStatus.value = e
})

onMounted(() => {
    getdata()
})

watch(() => props.device.id, c => {
    logtabledata.value = []
    logcount.value = 0
    offset.value = 0
    getdata()
})

watch(() => current.value, e => {
    getiotlogdata((e - 1) * 100)
    getlogcount()
})


function getdata() {
    getiotlogdata(0)
    getlogcount()
}

const loading2 = ref(false)

function download() {
    loading2.value = true
    FetchApi(assign({}, formInline, {
        query: `* | select * where devId in ('${props.device.id}') order by __time__ desc limit 0,${logcount.value}`,
    })).then(e => {

        const logtabledata = e.data.map((e: Ilogdata) => {
            const time = dayjs(Number(e['__time__']) * 1000).format('MM-DD HH:mm')
            const iot = props.device
            const name = iot?.name || ''
            if (e.protocol == 4) {
                const _category1 = props.tuyastate.find(t => t.name === props.device.category && e['status0code'] === t.code)
                const category1 = props.specificationStatus.find(c => c.code === e['status0code'])
                let value = e['status0value']
                if (_category1) {
                    category1.type = _category1.type
                    category1.name = _category1.dataname || category1.name
                    category1.options = _category1.options || category1.range?.map(c => {
                        return {
                            option: c,
                            value: c
                        }
                    })
                }
                if (iot) {
                    value = statedata2(e['status0value'], category1, iot)
                }
                let type = category1?.name

                return [
                    time,
                    name,
                    type,
                    value
                ]
            } else if (e.protocol == 20) {
                let type = '状态'
                let value = bizCode[e.bizcode]
                return [
                    time,
                    name,
                    type,
                    value
                ]
            } else {
                return [
                    time,
                    name,
                    '',
                    ''
                ]
            }
        })
        const _title = ['时间', '名称', ' 类型', '设备值']

        getExceltodownload([_title, ...logtabledata], '日志')
        loading2.value = false
    }).catch(e => {
        console.log(e)
        loading2.value = false
        ElMessage.error('下载失败')
    })
}

const line = ref(100)

</script>

<template>
    <a-tabs class="container" v-model:activeKey="activeName">
        <a-tab-pane key="function" tab="设备指令集">
            <a-table class="table" :columns="columns" :data-source="_specificationFunction" :pagination="false">
                <!-- <template slot="pop" slot-scope="text,record,index">
                    {{ JSON.stringify(JSON.parse(record), null, 2) }}
                </template> -->
            </a-table>
        </a-tab-pane>
        <a-tab-pane key="state" tab="设备状态集" force-render>
            <a-table class="table" :columns="columns" :data-source="_specificationStatus" :pagination="false">
            </a-table>
        </a-tab-pane>
        <a-tab-pane key="log" tab="设备日志" force-render>
            <div class="tab-pane">
                <div class="tab-pane-f">
                    <a-range-picker v-model:value="time" />
                    <a-button type="primary" @click="getdata">查询</a-button>
                    <a-tooltip placement="topRight">
                        <template #title>
                            <span>最多下载100页</span>
                        </template>
                        <a-button type="primary" @click="download">导出</a-button>
                    </a-tooltip>
                </div>
                <div class="tab-pane-m">
                    <a-table class="table" :loading="loading" :columns="logcolumns" :data-source="logtabledata"
                        :pagination="false">
                    </a-table>
                </div>

                <div class="tab-pane-f">
                    <a-pagination v-model:current="current" v-model:pageSize="line" :total="logcount"
                        :showSizeChanger="false" showQuickJumper />
                </div>
            </div>

        </a-tab-pane>
    </a-tabs>
</template>

<style scoped>
.container {
    width: 100%;
    position: relative;

}

.container .table {
    overflow: auto;
    height: calc(100vh - 130px);
    /*64(header) + 46(tabs) + 20(padding) = 130*/
}

.tab-pane {
    height: calc(100vh - 260px);
    display: flex;
    flex-direction: column;
}

.tab-pane .table {
    height: auto;
}

.tab-pane-m {
    flex: 1;
    overflow-y: auto;
}

.tab-pane-f {
    display: flex;
    align-items: center;
    justify-content: end;
    padding: 8px;
    gap: 24px;
}
</style>
